package com.itheima.reggie.service.impl;

import cn.hutool.core.util.ObjectUtil;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.domain.AddressBook;
import com.itheima.reggie.mapper.AddressBookMapper;
import com.itheima.reggie.service.AddressBookServicel;

import com.itheima.reggie.utils.UserThreadLocal;
import com.itheima.reggie.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class AddressBookServicelImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookServicel {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private AddressBookServicel addressBookServicel;

    /**
     * 设置用户默认地址
     *
     * @param param
     * @return
     */
    @Override
    public R defaultAddress(Map<String, String> param) {
        String id = param.get("id");
        //查询是否已存在默认地址
        AddressBook one = this.getOne(Wrappers.lambdaQuery(AddressBook.class).eq(AddressBook::getIsDefault, 1).eq(AddressBook::getUserId, UserThreadLocal.get().getId()));
        //如果有就把原来的默认地址改为非默认
        if (ObjectUtil.isNotNull(one)) {
            one.setIsDefault(0);
            this.updateById(one);
        }
        //再把当前的这个id对应的地址改为默认
        this.update(Wrappers.lambdaUpdate(AddressBook.class).eq(AddressBook::getId, id).set(AddressBook::getIsDefault, 1));

        return R.success("修改成功");
    }

    /**
     * 更新用户
     *
     * @param addressBook
     * @return
     */
    @Override
    public Object updateAddress(AddressBook addressBook) {

        this.updateById(addressBook);
        return R.success("修改成功");
    }
}
